import {Button, Space, Table, Pagination, Checkbox, Switch, Popconfirm, message} from 'antd'
import React, {useState} from 'react'
import {Link} from 'react-router-dom'
import stores from '../../../mobx/index'
import http from '../../../utils/http'


const TableList = ({list = [], history, getDate, ...props}) => {
  // 数据
  let [data, setData] = useState([])
  const [currentPage, setCurrentPage] = useState(1)
  const [isChecked, setiIsChecked] = useState(false)
  const [state, setState] = useState({selectedRowKeys: []})
  const {selectedRowKeys} = state

  const columns = [
    {
      title: '排序',
      dataIndex: 'queue',
      key: 'queue',
      render: (text, record, index) => (
        <div>{index + 1}</div>
      ),
    },
    {
      title: '商品',
      dataIndex: 'name',
      key: 'name',
      render: (text, record) => (
        <Space size="middle">
          <img className='goodsImg' src={record.image_url} alt="商品图" />
          <span className='ellipsisStyle'>{text}</span>
        </Space>
      ),
    },
    {
      title: '供货价',
      dataIndex: 'cost_price',
      key: 'cost_price',
      sorter: {
        compare: (a, b) => a.pri - b.pri,
        multiple: 3,
      },
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      key: 'create_time',
      sorter: {
        compare: (a, b) => a.chinese - b.chinese,
        multiple: 3,
      },
    },
    {
      title: '总库存',
      dataIndex: 'stoke',
      key: 'stoke',
      sorter: {
        compare: (a, b) => a.chinese - b.chinese,
        multiple: 3,
      },
    },
    {
      title: '销量',
      dataIndex: 'sall_num',
      key: 'sall_num',
      sorter: {
        compare: (a, b) => a.chinese - b.chinese,
        multiple: 3,
      },
    },
    {
      title: '推荐',
      dataIndex: 'switch',
      key: 'switch',
      render: (text, record) => (
        <Switch defaultChecked={text === 1 ? true : false} onChange={(checked) => onChange(checked, record)} />
      ),
    },
    {
      title: '操作',
      dataIndex: 'shelf',
      key: 'shelf',
      render: (text, record) => {
        return <Space size="middle" >
          <Button type="link" onClick={() => edit(record)}>编辑</Button>
          <Popconfirm
            title={`确定此商品${{0: '上架', 1: '下架'}[text]}吗?`}
            onConfirm={() => confirmShelf(text, record)}
            onCancel={() => cancelShelf(record)}
            okText="Yes"
            cancelText="No"
          >
            <span style={{color: '#1890ff', cursor: 'pointer'}} >{{0: '下架', 1: '上架'}[text]}</span>
          </Popconfirm>
          <Popconfirm
            title="确定删除此商品吗?"
            onConfirm={() => confirmDel(text, record)}
            onCancel={() => cancelDel(record)}
            okText="Yes"
            cancelText="No"
          >
            <span style={{color: '#1890ff', cursor: 'pointer'}}>删除</span>
          </Popconfirm>
        </Space>
      },
    },
  ]

  // 点击编辑跳转
  const edit = (record) => {
    history.push('/admin/product/list/addGoods?edit=true')
    sessionStorage.setItem('editData', JSON.stringify(record))
  }

  // 确定删除弹框
  const confirmDel = function(text, record) {
    message.success('商品已删除')
    console.log(record)
    http({
      url: '/huangyi/delGoods',
      method: 'post',
      data: {
        id: record.id
      }
    }).then(res => {
      console.log(res)
      getDate()
    })
  }

  // 取消删除弹框
  const cancelDel = function(e) {
    console.log(e)
    message.error('取消此商品删除')
  }

  // 取消上架弹框
  const cancelShelf = function(e) {
    console.log(e)
    message.error(`取消此商品${e.shelf === 1 ? '下架' : '上架'}`)

  }

  // 确定上架弹框
  const confirmShelf = function(text, record) {

    text = text === 1 ? 0 : 1
    record.shelf = text
    setData([...data])
    message.success(`商品已${text === 1 ? '上架' : '下架'}`)
    http({
      url: '/huangyi/editShelf',
      method: 'post',
      data: {
        shelf: text,
        id: record.id
      }
    }).then(res => {
      console.log(res)
    })
  }

  // 批量下架
  const AllShelf = () => {
    data.forEach(v => {
      v.shelf = 0
    })
    setData([...data])
    http({
      url: '/huangyi/editShelfes',
      method: 'post',
      data: {
        ids: selectedRowKeys,
      }
    }).then(res => {
      console.log(res)
      getDate()
      setState({
        selectedRowKeys: []
      })
    })
  }

  // 是否推荐
  const onChange = (checked, record) => {
    console.log(`switch to ${checked}`, record)
    http({
      url: '/huangyi/switchGoods',
      method: 'post',
      data: {
        id: record.id,
        switch1: checked ? 1 : 0
      }
    }).then(res => {
      console.log(res)
      getDate()
    })

  }

  // 全选时改变选中数组的值
  const onSelectChange = selectedRowKeys => {
    console.log('selectedRowKeys changed: ', selectedRowKeys)
    setState({selectedRowKeys})
  }

  // 全选按钮
  const allCheck = (checkedValue) => {
    console.log(checkedValue)
    if (checkedValue.target.checked) {
      let list = data.slice((currentPage - 1) * 5, (currentPage - 1) * 5 + 5)
      const keys = list.map(v => v.key)
      setState({selectedRowKeys: keys})
      setiIsChecked(true)
    } else {
      setState({selectedRowKeys: []})
      setiIsChecked(false)
    }
  }

  // 分页
  const onChangePage = (page, pageSize) => {
    console.log(page)
    setCurrentPage(page)
    setState({selectedRowKeys: []})
    setiIsChecked(false)
  }

  // 全选
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
    hideSelectAll: true
  }


  return (
    <>
      <Table
        rowSelection={rowSelection}
        columns={columns}
        dataSource={list}
        pagination={{
          position: [],
          current: currentPage,
          defaultPageSize: 5,
          total: list.length
        }}
        rowKey='id'
      />
      <div style={{padding: "16px 8px", display: 'flex', justifyContent: 'space-between'}}>
        <Space size="large">
          <Space>
            <Checkbox id="allcheck" checked={isChecked} onChange={allCheck} />
            <label htmlFor="allcheck" >全选</label>
          </Space>
          <Button type="primary" onClick={AllShelf}>批量下架</Button>
        </Space>
        <Pagination
          current={currentPage}
          total={list.length}
          onChange={onChangePage}
          defaultPageSize={5}
          showSizeChanger={false}
        />
      </div>
    </>
  )
}

export default TableList